package main

import (
	"cache"
	"errors"
	"log"
	"net/http"
)

var db = map[string]string{
	"Tom":  "100",
	"Jack": "101",
	"Sam":  "102",
}

// 数据源计数器
var loadCounts = make(map[string]int, len(db))

func main() {
	// @Todo 初始化DB
	cache.NewGroup("DB1", 2<<10, cache.GetterFunc(getHandler), cache.DeletedFunc(delHandler))

	// @Todo 创建httpServer
	addr := "192.168.11.213:9999"
	peer := cache.NewHttpPool(addr)
	log.Println("cache is running at ", addr)

	// @Todo 监听
	log.Fatal(http.ListenAndServe(addr, peer))
}

// getter 的handler方法
func getHandler(key string) ([]byte, error) {
	log.Println("[SlowDB] search key", key)
	if v, ok := db[key]; ok {
		if _, ok := loadCounts[key]; !ok {
			loadCounts[key] = 0
		}
		loadCounts[key] += 1
		return []byte(v), nil
	}
	return nil, errors.New("[SlowDB]" + key + " is not exist~")
}

func delHandler(key string) error {
	log.Println("[SlowDB] del key", key)
	return nil
}
